﻿namespace FKMC.Core.Configuration
{
    using System;
    using FluentNHibernate.Data;
    using NHibernate;
    using NHibernate.Type;

    public class EntityTimeStampInterceptor : EmptyInterceptor
    {
        public override bool OnSave(object entity, object id, object[] state,
            string[] propertyNames, IType[] types)
        {
            var entityTimeStamp = entity as Entity;

            if (entityTimeStamp == null)
                return false;

            for (int i = 0; i < propertyNames.Length; i++)
            {
                string propertyName = propertyNames[i];

                if (propertyName == "CreatedDate")
                {
                    state[i] = DateTime.Now;
                    return true;
                }
            }

            return true;
        }

        public override bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, IType[] types)
        {
            var entityTimeStamp = entity as Entity;

            if (entityTimeStamp == null)
                return false;

            for (int i = 0; i < propertyNames.Length; i++)
            {
                string propertyName = propertyNames[i];
                if (propertyName == "ModifiedDate")
                {
                    currentState[i] = DateTime.Now;
                    return true;
                }
            }

            return true;
        }


    }
}